package com.jingjin.humanityservice.util.ranking.cacheData;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * ClassName: CacheData
 * Description:
 *
 * @Author zjm
 */
@Component
public class CacheDataInRedis {

    @Resource
    private ObjectMapper objectMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public void cacheData(String key, Map<String, Object> data) {
        try {
            String jsonData = objectMapper.writeValueAsString(data);
            stringRedisTemplate.opsForValue().set(key, jsonData); // 不设置缓存时限，保证前端一定能访问到数据，后端则每三分钟刷新一次数据
        } catch (Exception e) {
            throw new RuntimeException("缓存数据失败", e);
        }
    }

    public Map<String, Object> getCachedData(String key) {
        String jsonData = stringRedisTemplate.opsForValue().get(key);
        if (jsonData != null) {
            try {
                return objectMapper.readValue(jsonData, Map.class);
            } catch (Exception e) {
                throw new RuntimeException("获取缓存数据失败", e);
            }
        }
        return null;
    }

}
